package com.shijunhao.graduation.service.scheduled;

import cn.hutool.core.collection.ConcurrentHashSet;
import com.shijunhao.graduation.domain.bean.HotInfoKey;
import com.shijunhao.graduation.domain.entity.SystemDictItem;
import com.shijunhao.graduation.enums.DictCode;
import com.shijunhao.graduation.service.business.IBusinessUserInfoService;
import com.shijunhao.graduation.service.system.ISystemDictService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: shijunhao
 * @date: 2022/5/8 2:36
 * @description:
 */
@Service
public class LooksScheduledService {

    @Resource
    private HotInfoScheduledService hotInfoScheduledService;
    @Resource
    private ISystemDictService systemDictService;
    @Resource
    private IBusinessUserInfoService userInfoService;

    private Logger logger = LoggerFactory.getLogger(LooksScheduledService.class);

    private Map<HotInfoKey, Set<Long>> looksRecords = new ConcurrentHashMap<>();

    @Scheduled(cron = "0 0,30 0 * * ?")
    @PreDestroy
    public void updateInfo() {
        //更新缓存
        Map<HotInfoKey, Set<Long>> newRecords = new ConcurrentHashMap<>();
        Map<HotInfoKey, Set<Long>> now = looksRecords;
        looksRecords = newRecords;
        //刷新热度信息到记录信息中
        for (Map.Entry<HotInfoKey, Set<Long>> entry : now.entrySet()) {
            Integer tableValue = entry.getKey().getTableValue();
            Long id = entry.getKey().getNid();
            hotInfoScheduledService.updateHotInfo(hotInfo -> hotInfo.setLooks(hotInfo.getLooks() + entry.getValue().size()), tableValue, id);
        }
        logger.info("访问量定时刷新成功！！");
    }

    /**
     * @param tableName: 表名
     * @param nid:       文章id
     * @return: void
     * @author: shijunhao
     * @date: 2022/5/8 2:49
     * @description:
     */
    public void userLook(String tableName, Long nid) {
        SystemDictItem item = systemDictService.loadByCodeLabel(DictCode.TABLE.getCode(), tableName);
        HotInfoKey hotInfo = new HotInfoKey(item.getDictValue(), nid);
        //添加当前文章信息访问情况
        Set<Long> res = looksRecords.computeIfAbsent(hotInfo, value -> new ConcurrentHashSet<>());
        //添加当前用户访问记录
        res.add(userInfoService.getCurrentUser().getId());
    }
}
